package com.lin.cms.web.controller;

import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lin.cms.common.web.ResponseUtils;
import com.lin.cms.core.tpl.TplManager;
import com.lin.cms.core.web.CoreUtils;
import com.lin.cms.criteria.GroupsCriteria;
import com.lin.cms.domain.Channel;
import com.lin.cms.domain.CmsUser;
import com.lin.cms.domain.Groups;
import com.lin.cms.domain.Model;
import com.lin.cms.domain.ModelItem;
import com.lin.cms.domain.Site;
import com.lin.cms.service.ChannelService;
import com.lin.cms.service.CmsUserService;
import com.lin.cms.service.GroupService;
import com.lin.cms.service.ModelItemService;
import com.lin.cms.service.ModelService;
import com.lin.cms.web.CmsUtils;
import com.lin.cms.web.WebErrors;

@Controller
public class ChannelController {
	private static final Logger log = LoggerFactory.getLogger(ChannelController.class);
	@RequestMapping("/channel/v_left.do")
	public String left() {
		return "channel/left";
	}
	
	@RequestMapping(value = "/channel/v_tree.do")
	public String tree(String root, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.debug("tree path={}", root);
		boolean isRoot;
		// jquery treeview的根请求为root=source
		if (StringUtils.isBlank(root) || "source".equals(root)) {
			isRoot = true;
		} else {
			isRoot = false;
		}
		model.addAttribute("isRoot", isRoot);
		WebErrors errors = validateTree(root, request);
		if (errors.hasErrors()) {
			log.error(errors.getErrors().get(0));
			ResponseUtils.renderJson(response, "[]");
			return null;
		}
		List<Channel> list;
		if (isRoot) {
			Site site = CmsUtils.getSite(request);
			list = channelService.getTopList(site.getSiteId(), false);
		} else {
			Integer rootId = Integer.valueOf(root);
			list = channelService.getChildList(rootId, false);
		}
		model.addAttribute("list", list);
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		return "channel/tree";
	}
	
	private WebErrors validateTree(String path, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		// if (errors.ifBlank(path, "path", 255)) {
		// return errors;
		// }
		return errors;
	}
	
	@RequestMapping("/channel/v_add.do")
	public String add(Integer root, Integer modelId,
			HttpServletRequest request, ModelMap model) {
		Site site = CmsUtils.getSite(request);
		Channel parent = null;
		if (root != null) {
			parent = channelService.selectByPrimaryKey(root);
			model.addAttribute("parent", parent);
			model.addAttribute("root", root);
		}
		// 模型
		Model m = cmsModelMng.selectByPrimaryKey(modelId);
		// 栏目模板列表
		List<String> channelTplList = getTplChannel(site, m, null);
		// 内容模板列表
		List<String> contentTplList = getTplContent(site, m, null);
		// 模型项列表
		List<ModelItem> itemList = cmsModelItemMng.getList(modelId, true,false);
		GroupsCriteria groupCriteria=new GroupsCriteria();
		List<Groups> groupList = cmsGroupMng.selectByCriteria(groupCriteria);
		// 浏览会员组列表
		List<Groups> viewGroups = groupList;
		// 投稿会员组列表
		Collection<Groups> contriGroups;
		if (parent != null) {
			contriGroups = parent.getContriGroups();
		} else {
			contriGroups = groupList;
		}
		// 管理员列表
		Collection<CmsUser> users;
		if (parent != null) {
			users = parent.getUsers();
		} else {
			users = cmsUserMng.getAdminList(site.getSiteId(), false, false, null);
		}
		model.addAttribute("channelTplList", channelTplList);
		model.addAttribute("contentTplList", contentTplList);
		model.addAttribute("itemList", itemList);
		model.addAttribute("viewGroups", viewGroups);
		model.addAttribute("contriGroups", contriGroups);
		model.addAttribute("contriGroupIds", Groups.fetchIds(contriGroups));
		model.addAttribute("users", users);
		model.addAttribute("userIds", CmsUser.fetchIds(users));
		model.addAttribute("model", m);
		return "channel/add";
	}
	
	@RequestMapping("/channel/v_list.do")
	public String list(Integer root, HttpServletRequest request, ModelMap model) {
		List<Channel> list;
		if (root == null) {
			list = channelService.getTopList(CmsUtils.getSiteId(request), false);
		} else {
			list = channelService.getChildList(root, false);
		}
		model.addAttribute("modelList", cmsModelMng.getList(false));
		model.addAttribute("root", root);
		model.addAttribute("list", list);
		return "channel/list";
	}
	
	@RequestMapping("/channel/v_edit.do")
	public String edit(Integer id, Integer root, HttpServletRequest request,
			ModelMap model) {
		Site site = CmsUtils.getSite(request);
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if (root != null) {
			model.addAttribute("root", root);
		}
		// 栏目
		Channel channel = channelService.selectByPrimaryKey(id);
		// 当前模板，去除基本路径
		int tplPathLength = site.getTplPath().length();
		String tplChannel = channel.getTplChannel();
		if (!StringUtils.isBlank(tplChannel)) {
			tplChannel = tplChannel.substring(tplPathLength);
		}
		String tplContent = channel.getTplContent();
		if (!StringUtils.isBlank(tplContent)) {
			tplContent = tplContent.substring(tplPathLength);
		}
		// 父栏目
		Channel parent = channel.getParent();
		// 模型
		Model m = channel.getModel();
		// 栏目列表
		List<Channel> topList = channelService.getTopList(site.getSiteId(), false);
		List<Channel> channelList = Channel.getListForSelect(topList, null,channel, false);

		// 栏目模板列表
		List<String> channelTplList = getTplChannel(site, m, channel.getTplChannel());
		// 内容模板列表
		List<String> contentTplList = getTplContent(site, m, channel.getTplContent());
		GroupsCriteria groupCriteria=new GroupsCriteria();
		List<Groups> groupList = cmsGroupMng.selectByCriteria(groupCriteria);
		// 模型项列表
		List<ModelItem> itemList = cmsModelItemMng.getList(m.getModelId(), true,false);
		// 浏览会员组列表、浏览会员组IDS
		List<Groups> viewGroups = groupList;
		Integer[] viewGroupIds = Groups.fetchIds(channel.getViewGroups());
		// 投稿会员组列表
		Collection<Groups> contriGroups;
		if (parent != null) {
			contriGroups = parent.getContriGroups();
		} else {
			contriGroups = groupList;
		}
		// 投稿会员组IDS
		Integer[] contriGroupIds = Groups.fetchIds(channel.getContriGroups());
		// 管理员列表
		List<CmsUser> users;
		if (parent != null) {
			users = parent.getUsers();
		} else {
			users = cmsUserMng.getAdminList(site.getSiteId(), false, false, null);
		}
		// 管理员IDS
		Integer[] userIds = channel.getUserIds();
		model.addAttribute("channelList", channelList);
		model.addAttribute("modelList", cmsModelMng.getList(false));
		model.addAttribute("tplChannel", tplChannel);
		model.addAttribute("tplContent", tplContent);
		model.addAttribute("channelTplList", channelTplList);
		model.addAttribute("contentTplList", contentTplList);
		model.addAttribute("itemList", itemList);
		model.addAttribute("viewGroups", viewGroups);
		model.addAttribute("viewGroupIds", viewGroupIds);
		model.addAttribute("contriGroups", contriGroups);
		model.addAttribute("contriGroupIds", contriGroupIds);
		model.addAttribute("users", users);
		model.addAttribute("userIds", userIds);
		model.addAttribute("channel", channel);
		model.addAttribute("model", m);
		return "channel/edit";
	}
	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Site site = CmsUtils.getSite(request);
		if (vldExist(id, site.getSiteId(), errors)) {
			return errors;
		}
		return errors;
	}
	private boolean vldExist(Integer id, Integer siteId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Channel entity = channelService.selectByPrimaryKey(id);
		if (errors.ifNotExist(entity, Channel.class, id)) {
			return true;
		}
		if (!entity.getSite().getSiteId().equals(siteId)) {
			errors.notInSite(Channel.class, id);
			return true;
		}
		return false;
	}
	
	private List<String> getTplChannel(Site site, Model model, String tpl) {
		String sol = site.getSolutionPath();
		List<String> tplList = tplManager.getNameListByPrefix(model.getTplChannel(sol, false));
		return CoreUtils.tplTrim(tplList, site.getTplPath(), tpl);
	}
	private List<String> getTplContent(Site site, Model model, String tpl) {
		String sol = site.getSolutionPath();
		List<String> tplList = tplManager.getNameListByPrefix(model.getTplContent(sol, false));
		return CoreUtils.tplTrim(tplList, site.getTplPath(), tpl);
	}
	
	@Autowired
	private ChannelService channelService;
	@Autowired
	private TplManager tplManager;
	@Autowired
	private ModelItemService cmsModelItemMng;
	@Autowired
	private GroupService cmsGroupMng;
	@Autowired
	private CmsUserService cmsUserMng;
	@Autowired
	private ModelService cmsModelMng;
}
